<script setup>

// 搜索关键词
import {Delete, Edit, Lock, Message, Plus, Refresh, Search, User} from "@element-plus/icons-vue";
import {onMounted, reactive, ref} from "vue";
import {post} from '@/net/index.js'
import {ElMessage, ElMessageBox} from "element-plus";

// 当前页数
const currentPage = ref(1);
// 每页多少条
const pageSize = ref(10);
// 共计多少条
const total = ref(0);
// 查询出来的数据
const dataList = ref([]);
// 存放当前选取的数据
const multipleSelection = ref([])
// 新增表单显示
const addDialog = ref(false);
// 修改表单显示
const editDialog = ref(false);
// 表单标签位置
const labelPosition = ref('top');
// 搜索关键词
const searchKeyword = reactive({
    userName: '',
    userMail: '',
    userRole: '',
});
// 表单内数据
const createForm = reactive({
    id: '',
    userName: '',
    userPassword: '',
    userMail: '',
    userRole: ''
});

// 新增用户
const handleAddConfirm = () => {
    post('/api/user/add',
        {
            username: createForm.userName,
            password: createForm.userPassword,
            userRole: createForm.userRole,
            usermail: createForm.userMail,
        },
        () => {
            // 处理成功的情况
            ElMessage({
                message: "新增用户成功！",
                type: "success",
            })
            // 关闭表单窗口
            addDialog.value = false;
            // 清除表单上的数据
            cleanForm();
            // 刷新数据
            loadData(currentPage, pageSize)
        }
    )
};
// 关闭窗口处理
const dialogClose = () => {
    ElMessageBox.confirm('您有数据未保存，确定关闭窗口？', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
    })
        .then(() => {
            // 关闭窗口
            addDialog.value = false;
            editDialog.value = false
            // 清空表单中的数据
            cleanForm();
        })
        .catch(() => {
            // 不关闭窗口
        })
}
// 用户名校验函数
const validateUsername = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请输入用户名'))
    } else if(!/^[a-zA-Z0-9\u4e00-\u9fa5]+$/.test(value)){
        callback(new Error('用户名不能包含特殊字符，只能是中文/英文'))
    } else {
        callback()
    }
}
// 编辑表单校验规则
const editRules = {
    userName: [
        { validator: validateUsername,required: true , trigger: ['blur', 'change'] },
        { min: 2, max: 8, message: '用户名的长度必须在2-8个字符之间', trigger: ['blur', 'change'] },
    ],
    userMail: [
        { required: true, message: '请输入邮件地址', trigger: 'blur' },
        {type: 'email', message: '请输入合法的电子邮件地址', trigger: ['blur', 'change']}
    ]
}
// 新增用户表单校验规则
const addRules = {
    userName: [
        {required: true, validator: validateUsername, trigger: ['blur', 'change']},
        {min: 2, max: 8, message: '用户名的长度必须在2-8个字符之间', trigger: ['blur', 'change']},
    ],
    userPassword: [
        {required: true, message: '请输入密码', trigger: 'blur'},
        {min: 6, max: 16, message: '密码的长度必须在6-16个字符之间', trigger: ['blur', 'change']}
    ],
    userMail: [
        {required: true, message: '请输入邮件地址', trigger: 'blur'},
        {type: 'email', message: '请输入合法的电子邮件地址', trigger: ['blur', 'change']}
    ]
}
// 编辑用户
const handleEditConfirm = () => {
    post('/api/user/update',
        {
            id: createForm.id,
            username: createForm.userName,
            usermail: createForm.userMail,
            userRole: createForm.userRole,
        },
        () => {
            // 处理成功的情况
            ElMessage({
                message: "编辑用户成功！",
                type: "success",
            })
            // 关闭表单窗口
            editDialog.value = false;
            // 清除表单上的数据
            cleanForm();
            // 刷新数据
            loadData(currentPage, pageSize)
        }
    );
};
// 点击编辑
const handleEdit = (index, row) => {
    // 显示编辑表单
    editDialog.value = true
    // 数据回显至表单
    createForm.id = row.id;
    createForm.userName = row.username;
    createForm.userMail = row.usermail;
    createForm.userRole = row.userRole;
}
// 清空表单中数据
const cleanForm = () => {
    createForm.userName = '';
    createForm.userMail = '';
    createForm.userRole = '';
}
// 关闭表单窗口时提示
const handleClose = () => {
    // 清空表单中的数据
    cleanForm();
}
// 格式化时间
const formatDate = (row, column, cellValue) => {
    if (cellValue) {
        return cellValue.substring(0, 10); // 返回前10个字符，即"yyyy-MM-dd"的格式
    }
    return "";
}
// 删除用户
const handleDelete = (index, row) => {
    ElMessageBox.confirm('确定要删除该用户吗？', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
    })
        .then(() => {
            post('/api/user/delete/',
                {
                    idList: [row.id],
                },
                () => {
                    ElMessage({
                        message: "删除用户成功！",
                        type: "success",
                    })
                    // 刷新数据
                    loadData(currentPage, pageSize)
                    // 关闭表单窗口
                    addDialog.value = false;
                }
            );
        })
        .catch(() => {
            // 不关闭窗口
        })
}
// 搜索用户
const onSearch = (page) => {
    if (searchKeyword.userName === "" && searchKeyword.userRole === "" && searchKeyword.userMail === "") {
        ElMessage({
            message: "请输入关键词！",
            type: "warning",
        })
    } else {
        post('/api/user/list/page/',
            {
                username:  searchKeyword.userName,
                userRole:  searchKeyword.userRole,
                usermail:  searchKeyword.userMail,
                current: currentPage.value,
                pageSize: pageSize.value
            },
            (data) => {
                dataList.value = data.records;
                total.value = data.total;
                currentPage.value = page.value // 更新当前页码
            }
        );
    }
};
// 重置表格数据
const resetData = (page) => {
    // 清空搜索框中数据
    searchKeyword.userName = '';
    searchKeyword.userRole = '';
    searchKeyword.userMail = '';
    // 调用后端接口获取数据
    loadData(page, pageSize.value)
}
// 获取行键
const getRowKeys = (row) => {
    //唯一标识id，也可以是你自己数据源中的其他某个代表唯一的字段
    return row.id
}
// 状态变化触发
const handleSelectionChange = (val) => {
    multipleSelection.value = val
}
// 页数变化时
const handleCurrentPageChange = (page) => {
    currentPage.value = page;
    // 调用后端接口获取数据
    loadData(page, pageSize.value)
}
// 从后端获取数据
const loadData = (page, pageSize) => {
    post('/api/user/list/page/',
        {
            current: currentPage.value,
            pageSize: pageSize.value
        },
        (data) => {
            dataList.value = data.records;
            total.value = data.total;
        }
    );
};

onMounted(() => {
    // 初始化加载数据
    loadData(currentPage, pageSize)
});
</script>

<template>
    <!--搜索框-->
    <div class="searchBox">
        <el-form :inline="true" :model="searchKeyword" size="large">
            <el-form-item style="margin: 0 10px">
                <span class="searchTitle">用户名称</span>
                <el-input v-model="searchKeyword.userName" placeholder="请输入用户名称" clearable style="width: 150px;"/>
            </el-form-item>
            <el-form-item style="margin: 0 10px">
                <span class="searchTitle">用户邮箱</span>
                <el-input v-model="searchKeyword.userMail" placeholder="请输入用户邮箱" clearable style="width: 150px;"/>
            </el-form-item>
            <el-form-item style="margin: 0 10px">
                <span class="searchTitle">用户角色</span>
                <el-select v-model="searchKeyword.userRole" placeholder="请选择用户角色" style="width: 150px;">
                    <el-option label="普通用户" value="user"/>
                    <el-option label="管理员" value="admin"/>
                </el-select>
            </el-form-item>
            <el-form-item style="margin: 0 10px">
                <el-button type="primary" :icon="Search" @click="onSearch">搜索</el-button>
            </el-form-item>
            <el-form-item style="margin: 0 10px">
                <el-button type="success" :icon="Refresh" @click="resetData">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
    <!--表格板块-->
    <div class="tableBlock">
        <div class="operateBox">
            <div class="OperationButton" >
                <el-button type="success" :icon="Plus" class="button" @click="addDialog=true">新增</el-button>
            </div>
        </div>
        <div id="showTable">
            <!--表格-->
            <el-table
                :row-key="getRowKeys"
                @selection-change="handleSelectionChange"
                :data="dataList"
                style="font-family: shangshou;font-size: 17px;font-weight: bold"
                :default-sort="{ prop: 'createTime', order: 'asc' }" border>
                <el-table-column label="序号" type="index" width="60" align="center" />
                <el-table-column label="用户名称" width="100" prop="username"/>
                <el-table-column label="用户邮箱" width="180" prop="usermail"/>
                <el-table-column label="用户角色" width="90" prop="userRole">
                    <template #default="scope">
                        <el-tag v-if="scope.row.userRole === 'user'" type="primary" style="width: 50px">普通用户</el-tag>
                        <el-tag v-if="scope.row.userRole === 'admin'" type="danger" style="width: 50px">管理员</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="AccessKey" width="300" prop="accessKey"/>
                <el-table-column label="SecretKey" width="300" prop="secretKey"/>
                <el-table-column label="创建时间" width="120" prop="createTime" :formatter="formatDate" sortable >
                </el-table-column>
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button size="small" type="primary" :icon="Edit"
                                   @click="handleEdit(scope.$index, scope.row)">
                            编辑
                        </el-button>
                        <el-button size="small" type="danger" :icon="Delete"
                                   @click="handleDelete(scope.$index, scope.row)">
                            删除
                        </el-button>
                        <!--    <el-button size="small" type="info" :icon="Lock"
                                   @click="handleBackList(scope.$index, scope.row)">
                            拉入黑名单
                        </el-button>-->
                    </template>
                </el-table-column>
            </el-table>
            <!--分页器-->
            <el-pagination
                background
                style="margin-top: 15px"
                :current-page="currentPage"
                :page-size="pageSize"
                :total="total"
                @current-change="handleCurrentPageChange"
                layout="prev, pager, next, total"
            ></el-pagination>
        </div>
    </div>

    <!--新增用户信息表单-->
    <el-dialog v-model="addDialog" title="添加用户" width="40%" style="color: #909399" @close="handleClose">
        <el-form :model="createForm" :label-position="labelPosition" :rules="addRules" status-icon>
            <el-form-item label="用户名称" prop="userName">
                <el-input v-model="createForm.userName" placeholder="请输入用户名称" type="text" :prefix-icon="User"/>
            </el-form-item>
            <el-form-item label="用户密码" prop="userPassword">
                <el-input v-model="createForm.userPassword" placeholder="请输入用户密码" type="text" :prefix-icon="Lock"/>
            </el-form-item>
            <el-form-item label="用户邮箱" prop="userMail">
                <el-input v-model="createForm.userMail" placeholder="请输入用户邮箱" type="text" :prefix-icon="Message"/>
            </el-form-item>
            <el-form-item label="用户角色" prop="userRole">
                <el-select v-model="createForm.userRole" placeholder="请选择用户角色" >
                    <el-option label="普通用户" value="user"/>
                    <el-option label="管理员" value="admin"/>
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button type="danger" @click="dialogClose" class="button">取消</el-button>
            <el-button type="success" @click="handleAddConfirm" class="button">确认</el-button>
        </template>
    </el-dialog>
    <!--编辑用户信息表单-->
    <el-dialog v-model="editDialog" title="编辑用户" width="40%" style="color: #909399" @close="handleClose">
        <el-form :model="createForm" :label-position="labelPosition" :rules="editRules" status-icon>
            <el-form-item label="用户名称" prop="userName">
                <el-input v-model="createForm.userName" placeholder="请输入用户名称" type="text" :prefix-icon="User"/>
            </el-form-item>
            <el-form-item label="用户邮箱" prop="userMail">
                <el-input v-model="createForm.userMail" placeholder="请输入用户邮箱" type="text" :prefix-icon="Message"/>
            </el-form-item>
            <el-form-item label="用户角色" prop="userRole">
                <el-select v-model="createForm.userRole" placeholder="请选择用户角色" >
                    <el-option label="普通用户" value="user"/>
                    <el-option label="管理员" value="admin"/>
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button type="danger" @click="dialogClose" class="button">取消</el-button>
            <el-button type="success" @click="handleEditConfirm" class="button">确认</el-button>
        </template>
    </el-dialog>
</template>

<style scoped>
@font-face {
    font-family: "Sphere fez"; /* 定义字体名称 */
    src: url('/src/assets/font/spherefez-ezxam.ttf') format('truetype'); /* 指定字体文件的路径和格式 */
}

@font-face {
    font-family: "shangshou"; /* 定义字体名称 */
    src: url('/src/assets/font/上首简黑极细体.ttf') format('truetype'); /* 指定字体文件的路径和格式 */
}

.searchTitle {
    color:#909399;
    font-size: 20px;
    margin-right: 10px;
    font-weight: bold;
    font-family: shangshou;
}
</style>